/*
 * ProfilesManagerBean.java
 *
 * Created on 4 październik 2007, 19:49
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package info.mikrotubula.managers;

import info.mikrotubula.db.Profiles;
import info.mikrotubula.db.Rights;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Krystian
 */
@Stateless
public class ProfilesManagerBean implements info.mikrotubula.managers.ProfilesManagerLocal {
    
    @PersistenceContext(unitName = "persistence")
    protected EntityManager em;   
    
    /** Creates a new instance of ProfilesManagerBean */
    public ProfilesManagerBean() {
    }
    
    public List<Profiles> list() {
        return (List<Profiles>) em.createNamedQuery("Profiles.findAll").getResultList();
    }
    
    public Profiles create(Profiles profile) {
        try {
            em.persist(profile);
            return profile;
        } catch (Exception e) {
            e.printStackTrace();
            return new Profiles();
        }
    }
    
    public Boolean checkIfExists(Profiles profile) {
        List<Profiles> list = (List<Profiles>) em.createNamedQuery("Profiles.findByPrfName")
                .setParameter("prfName", profile.getPrfName())
                .getResultList();
        if (list == null || list.isEmpty()) return false;
        return true;
    }
    
    public Profiles findById(Profiles profile) throws NoResultException, NonUniqueResultException {
        return (Profiles) em.createNamedQuery("Profiles.findByPrfId")
                .setParameter("prfId", profile.getPrfId())
                .getSingleResult();
    }
    
    public void saveProfileRights(Profiles profile, List<Rights> rights) {
        //najpierw usuwam wszystkie po��czenia
        em.createNativeQuery("DELETE FROM PROFILE_RIGHTS WHERE PR_PRF_ID=#prfId")
                .setParameter("prfId", profile.getPrfId())
                .executeUpdate();
        //wi��e profil        
        em.merge(profile);
        //wi��e z ka�dym uprawnieniem
        for (Rights right : rights) {
            if (!right.getSelected()) continue; //je�eli nie wybrany, to pomijamy
            Rights rightToMerge = em.find(Rights.class, right.getRghId());
            profile.addRight(rightToMerge);
        }
        em.merge(profile);
    }
    
}
